package com.itheima.test;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer02 {
    private final static String EXCHANGE_FANOUT = "publishSubscribe";
    private final static String QUEUE_MESSAGE = "shortMessage";
    private final static String QUEUE_INFOR = "information";


    public static void main(String[] args) {
//        通过工厂获取连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
//        设置工厂属性
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
//        创建与rabbit服务器的连接
        try {
            connection = connectionFactory.newConnection();
//            创建与交换机的连接通道，每个连接可以创建多个通道，每个通到代表一个会话任务

            Channel channel = connection.createChannel();
//            声明一个交换机
//            String exchange, String type
//            交换机名称，交换机类型
//            FANOUT：发布订阅模式
            channel.exchangeDeclare(EXCHANGE_FANOUT, BuiltinExchangeType.FANOUT);

//            生命队列
//            String queue, boolean durable, boolean exclusive, boolean autoDelete,Map<String, Object> arguments
//           对列参数：队列名称，是否持久化，是否独占，是否不用时自动删除，队列参数设置
            channel.queueDeclare(QUEUE_MESSAGE, true, false, false, null);
            channel.queueDeclare(QUEUE_INFOR, true, false, false, null);
//              路由和交换机的绑定
            channel.queueBind(QUEUE_MESSAGE,EXCHANGE_FANOUT,"");
            channel.queueBind(QUEUE_INFOR,EXCHANGE_FANOUT,"");
            for (int i = 0; i < 5; i++) {
//            要发送的消息体
            String msg="hello world"+System.currentTimeMillis();
//            消息发布
//            String exchange, String routingKey, BasicProperties props, byte[] body
//            交换机名称，消息路由的key,消息包含的属性，消息体
            channel.basicPublish(EXCHANGE_FANOUT,"",null,msg.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {

        }
    }
}
